package org.audio.tcpspeaker;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import org.audio.tcpspeaker.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.net.UnknownHostException;
import java.time.Duration;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    public volatile boolean connStatus=false;
    private EditText ip;
    private EditText port;
    public Button connect1;
    private Intent servIntent;
    private MyForegroundServReceiver mReceiver;
    private volatile MyForegroundServ.mBinder mbind=null;
    private ServiceConnection connection = new ServiceConnection() {
          @Override
         // 活动和服务的绑定失去的时候自动调用，比如服务被杀死或者报错，这时候ServiceConnection会保持**，在活动下次启动时会收到一个通知
         public void onServiceDisconnected(ComponentName name) {
            mbind=null;
         }
         @Override
         // 活动和服务解绑的时候自动调用，即bindService()函数调用时
         public void onServiceConnected(ComponentName name, IBinder service) {
              mbind = (MyForegroundServ.mBinder) service; // 通过Service向下转型得到一个MyService.mBinder的对象
            if (mbind!=null) {
                Log.d("MyForegroundServ:", "onServiceConnected mbind not null");
            }
             if(mbind != null) {
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                             mbind.update_ui();
                     }
                 });

             }

         }
      };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        ip=findViewById(R.id.IP);
        port=findViewById(R.id.Port);
        connect1=findViewById(R.id.Connet);
        connect1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                saveAddress();
                /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mbind.update_ui();
                    }
                }).start();*/

                if (connStatus==false) {
                    String ip1 = ip.getText().toString();
                    String port1s = port.getText().toString();
                    if (ip1.length()==0 || port1s.length()==0) {
                        return;
                    }
                    int port1 = Integer.parseInt(port1s);
                    //startService( servIntent );
                    //bindService(servIntent, connection, BIND_AUTO_CREATE);
                    //Toast.makeText(getApplicationContext(),"start service and bind",Toast.LENGTH_LONG).show();

                    if (mbind!=null) {
                        mbind.connect(ip1, port1);
                    }else{
                        Log.d("MainActivity", "mbind=null");
                        Toast.makeText(getApplicationContext(),"Not ready yet, try later.",Toast.LENGTH_LONG).show();
                    }


                } else {
                    mbind.disconnect();
                }

            }
        });
        SharedPreferences sp = getSharedPreferences("Address",MODE_PRIVATE);
        String addr1=sp.getString("Address","none");
        if(addr1 != "none") {
            String[] a=addr1.split("[:]");
            if (a.length==2) {
                ip.setText(a[0]);
                port.setText(a[1]);
            }
        }
        //注册广播信息接收类
        mReceiver = new MyForegroundServReceiver();
        IntentFilter f1 = new IntentFilter();
        f1.addAction("connected");
        f1.addAction("disconnected");
        registerReceiver(mReceiver, f1);
        Toast.makeText(getApplicationContext(),"register receiver",Toast.LENGTH_LONG).show();

        //运行service
        servIntent = new Intent(this, MyForegroundServ.class);
        startService( servIntent );
        bindService(servIntent, connection, BIND_AUTO_CREATE);
        //Toast.makeText(getApplicationContext(),"start service and bind",Toast.LENGTH_LONG).show();
    }

    public void saveAddress(){
        SharedPreferences sp = getSharedPreferences("Address",MODE_PRIVATE);
        SharedPreferences.Editor ed=sp.edit();
        String v=ip.getText().toString()+":"+port.getText().toString();
        ed.putString("Address",v);
        ed.commit();
        //Snackbar.make(port, v, Snackbar.LENGTH_LONG)
               // .setAction("Action", null).show();
    }

    @Override
    public void onDestroy() {
        if (connStatus==false) {
            stopService(servIntent);
        }
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class MyForegroundServReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context cxt, Intent itt){
            //update UI
            switch (itt.getAction()) {
                case "connected":
                    connStatus=true;
                    connect1.setText("DISCONNECT");
                    Log.d("MainActivity:", "set status connected");
                    break;
                case "disconnected":
                    connStatus=false;
                    connect1.setText("CONNECT");
                    Log.d("MainActivity:", "set status disconnected");
                    break;
            }
        }
    }

}